//
//  JBarberShopViewController.m
//  HeadIndustry
//
//  Created by jun on 2017/8/24.
//  Copyright © 2017年 jun. All rights reserved.
//

#import "JBarberShopViewController.h"
#import "UITableView+JFTableView.h"
#import "JCutHairShopCell.h"
#import "JCutHairHeadView.h" // 透明层
#import "JEmptyDataView.h" // 空视图
#import "JCutHairDetailController.h" //
#import "JMsgController.h"
#define TableViewheight (self.contentView.height - 40 - 50) // 透明层 列表高度

@interface JBarberShopViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource >
@property (nonatomic, strong) JCutHairRequestModel *headRequestModel;
@property (nonatomic, strong) JCutHairHeadView *headTableView; // 透明层
@property (nonatomic, strong) JEmptyDataView *emptyView; // 空视图
@property (nonatomic, strong) JCutHairShopModel *shopModel;
@property (nonatomic, assign) NSInteger selBtnType;  // 0 全城  1 距离   2 排序
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSMutableArray *btnArr;

@property (nonatomic, copy) NSArray *listAreaArr; // 区域
@property (nonatomic, copy) NSArray *listDesArr; // 距离
@property (nonatomic, copy) NSArray *listSortArr; // 排序

@property (nonatomic, copy) NSArray *listSelArr;


@end

@implementation JBarberShopViewController

- (JEmptyDataView *)emptyView
{
    if (_emptyView == nil) {
        _emptyView = [[JEmptyDataView alloc]initWithFrame:CGRectMake(0, 40, kWindowW, TableViewheight)];
        _emptyView.titleStr = @"该搜索范围内没有找到理发店店铺！";
    }
    return _emptyView;
}

- (NSArray *)listDesArr
{
    if (_listDesArr == nil) {
        _listDesArr = @[@"< 1千米",@"< 2千米",@"< 3千米",@"< 5千米",@"< 10千米"];
    }
    return _listDesArr;
}

- (NSArray *)listSortArr
{
    if (_listSortArr == nil) {
        _listSortArr = @[@"离我最近",@"人气最高",@"最新发布"];
    }
    return _listSortArr;
}

- (JCutHairHeadView *)headTableView
{
    if (_headTableView == nil) {
        _headTableView = [[JCutHairHeadView alloc]initWithFrame:CGRectMake(0, 40, kWindowW,  TableViewheight)];
        __weak typeof(self) weakSelf = self;
        
        _headTableView.cancelBlock = ^{
            [weakSelf ProductTypeViewAnimation:NO];
            for (UIButton *btn in weakSelf.btnArr) {
                btn.selected = NO;
            }
        };
        
        _headTableView.productTypeBlock = ^(NSString *shopNameTip, NSInteger num) {
            [weakSelf ProductTypeViewAnimation:NO];
            for (UIButton *btn in weakSelf.btnArr) {
                btn.selected = NO;
            }
            
            UIButton *btn1 = [weakSelf.btnArr objectAtIndex:weakSelf.selBtnType];
            [btn1 setTitle:shopNameTip forState:UIControlStateNormal];
            
            weakSelf.headRequestModel.PageIndex = 1;
            [weakSelf.dataArr removeAllObjects];
            
            
            if (weakSelf.selBtnType == 0) {
                if (num == 0) {
                    weakSelf.headRequestModel.Area = @"";
                    
                }
                else
                {
                    weakSelf.headRequestModel.Area = shopNameTip;
                }
                
                weakSelf.headRequestModel.Distince = 0;
                UIButton *btn1 = [weakSelf.btnArr objectAtIndex:1];
                [btn1 setTitle:@"距离" forState:UIControlStateNormal];
                
            }
            if (weakSelf.selBtnType == 1) {
                weakSelf.headRequestModel.Area = @"";
                UIButton *btn1 = [weakSelf.btnArr objectAtIndex:0];
                [btn1 setTitle:@"全城" forState:UIControlStateNormal];
                
                if (num == 0) {
                    weakSelf.headRequestModel.Distince = 1;
                }
                else if (num == 1) {
                    weakSelf.headRequestModel.Distince = 2;
                }
                else if (num == 2) {
                    weakSelf.headRequestModel.Distince = 3;
                }
                else if (num == 3) {
                    weakSelf.headRequestModel.Distince = 5;
                }
                else if (num == 4) {
                    weakSelf.headRequestModel.Distince = 10;
                }
            }
            if (weakSelf.selBtnType == 2) {
                if (num == 0) {
                    weakSelf.headRequestModel.Order = 1;
                }
                else if (num == 1) {
                    weakSelf.headRequestModel.Order = 2;
                }
                else if (num == 2) {
                    weakSelf.headRequestModel.Order = 3;
                }
                
            }
            
            [weakSelf loadCutHairShopDataRequest];
        };
        
    }
    return _headTableView;
}

- (JCutHairRequestModel *)headRequestModel
{
    if (_headRequestModel == nil) {
        _headRequestModel = [JCutHairRequestModel new];
        _headRequestModel.PageSize = 10;
        _headRequestModel.PageIndex = 1;
        _headRequestModel.Order = 1;
        _headRequestModel.Distince = 0;
        _headRequestModel.UserId = [GLOBALDATA userInfoModel].CustomerId;
        _headRequestModel.CustomerId = [GLOBALDATA userInfoModel].CustomerId;
        
        if ([[NSUserDefaults standardUserDefaults] objectForKey:UserLocationCity]) {
            NSDictionary *cityDic = [[NSUserDefaults standardUserDefaults] objectForKey:UserLocationCity];
            
            _headRequestModel.City = cityDic[@"cityName"];
            _headRequestModel.Lat = [NSString stringWithFormat:@"%.8f",[cityDic[@"cityLocationLat"] doubleValue]];
            _headRequestModel.Lng = [NSString stringWithFormat:@"%.8f",[cityDic[@"cityLocationLng"] doubleValue]];
            
        }
        else
        {
            _headRequestModel.City = @"武汉市";
        }
        
    }
    return _headRequestModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [super InitUI];
    self.titleLabel.hidden = YES;
    self.leftButton.hidden = NO;
    self.rightButton.hidden = NO;
    _listAreaArr = [NSArray array];
    _listSelArr = [NSArray array];
    
    _dataArr = [NSMutableArray array];
    _btnArr = [NSMutableArray array];

    [self setUpNav];  // 导航栏
    [self setTopBtnSelConfigView]; // 上方按钮
    [self setConfigTableView]; // tableView
    [self loadCutHairShopAreaRequest];
    
    [self.contentView addSubview:self.emptyView]; // 空数据
    self.emptyView.hidden = YES;
    [self.contentView addSubview:self.headTableView]; // 灰层 列表
    self.headTableView.hidden = YES;
    
}

// 配置导航栏
- (void)setUpNav
{
    NSString *userCity;
    if ([UserDefaultsDelegate objectForKey:UserLocationCity] != nil) {
        NSDictionary *cityDic = [[NSUserDefaults standardUserDefaults] objectForKey:UserLocationCity];
        userCity = cityDic[@"cityName"];
    }
    else
    {
        userCity = @"武汉市";
    }
    
    [self.leftButton setTitle:userCity forState:UIControlStateNormal];
    [self.rightButton setImage:[UIImage imageNamed:msgBtnImg] forState:UIControlStateNormal];
    
    CGRect searchRect = CGRectMake(CGRectGetMaxX(self.leftButton.frame), 25, CGRectGetMinX(self.rightButton.frame) - CGRectGetMaxX(self.leftButton.frame), 32);
    
    UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:searchRect];
    searchBar.delegate = self;
    searchBar.backgroundColor = [UIColor clearColor];
    
    searchBar.placeholder = @"店铺搜索";
//    searchBar.showsSearchResultsButton = YES;

    for (UIView *subViews in searchBar.subviews) {
        if ([subViews isKindOfClass:[UIView class]]) {
            [[subViews.subviews objectAtIndex:0] removeFromSuperview];
            
            if ([[subViews.subviews objectAtIndex:0] isKindOfClass:[UITextField class]]) {
                UITextField *textF = [subViews.subviews objectAtIndex:0];
                textF.font = kFONT_TITLE(12);
                textF.backgroundColor = kRGBColor(240, 240, 240);
                
                UIColor *color = [UIColor grayColor];
                NSAttributedString *attri = [[NSAttributedString alloc]initWithString:@"店铺搜索" attributes:@{NSForegroundColorAttributeName:color}];
                
                [textF setAttributedPlaceholder:attri];
            }
        }
    }
    //    [searchBar setShowsCancelButton:YES];
    [self.navigationView addSubview:searchBar];
    
}

- (void)setTopBtnSelConfigView {
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.contentView.width, 40)];
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:bottomView];
    
    NSArray *nameArr = @[@"全城",@"距离",@"智能排序"];
    CGFloat selbtnWidth = bottomView.width/3.0;
    
    for (int i = 0; i < nameArr.count; i++) {
        UIButton *collectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        collectBtn.frame = CGRectMake(selbtnWidth * i , 0, selbtnWidth, 40);
        collectBtn.titleLabel.font = kFONT_TITLE(14);
        [collectBtn setTitle:nameArr[i] forState:UIControlStateNormal];
        [collectBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [collectBtn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        collectBtn.tag = 10 + i;
        
        [collectBtn addTarget:self action:@selector(collectBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        collectBtn.selected = NO;
        
        [collectBtn setImage:[UIImage imageNamed:@"up"] forState:UIControlStateNormal];
        [collectBtn setImage:[UIImage imageNamed:@"down"] forState:UIControlStateSelected];
    
        [collectBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -30, 0, 0)];
        [collectBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 93, 0, 5)];
    
        
        [bottomView addSubview:collectBtn];
        [_btnArr addObject:collectBtn];
    }
    CALayer *line1 = [CALayer layer];
    line1.backgroundColor = kRGBColor(150, 150, 150).CGColor;
    line1.frame = CGRectMake(selbtnWidth-0.5, 0 , 1, bottomView.height);
    [bottomView.layer addSublayer:line1];
    
    CALayer *line2 = [CALayer layer];
    line2.backgroundColor = kRGBColor(150, 150, 150).CGColor;
    line2.frame = CGRectMake(selbtnWidth*2-0.5, 0 , 1, bottomView.height);
    [bottomView.layer addSublayer:line2];
    
    
    CALayer *line = [CALayer layer];
    line.backgroundColor = kRGBColor(150, 150, 150).CGColor;
    line.frame = CGRectMake(0, bottomView.bottom - 0.5 , kWindowW, 0.5);
    [bottomView.layer addSublayer:line];
    
}

- (void)setConfigTableView {
    _tableView = [UITableView initWithTableView:CGRectMake(0, 40, kWindowW, self.contentView.height - 40 - 49) withDelegate:self];
    [self.contentView addSubview:_tableView];
    
    _tableView.rowHeight = kWindowW/3.0 + 20 + 10;
    [_tableView registerClass:[JCutHairShopCell class] forCellReuseIdentifier:NSStringFromClass([JCutHairShopCell class])];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (self.dataArr.count == self.headRequestModel.PageIndex * self.headRequestModel.PageSize) {
            self.headRequestModel.PageIndex += 1;
            [self loadCutHairShopDataRequest];
            [_tableView.mj_footer endRefreshing];
        }
        else if (self.dataArr.count == 0)
        {
            [self loadCutHairShopDataRequest];
            [_tableView.mj_footer endRefreshing];
        }
        else
        {
            [_tableView.mj_footer endRefreshingWithNoMoreData];
        }
    }];
    
    [_tableView.mj_footer beginRefreshing];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JCutHairShopCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([JCutHairShopCell class]) forIndexPath:indexPath];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if (self.dataArr.count > indexPath.row) {
            cell.shopModel = self.dataArr[indexPath.row];
        }
    });
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.view endEditing:YES];
    JCutShopDetailModel *shopModel = self.dataArr[indexPath.row];
    JCutHairDetailController *detailVC = [[JCutHairDetailController alloc]init];
    detailVC.CutHairShopId = shopModel.BarberShopId;
    detailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - buttonClick

- (void)collectBtnClick:(UIButton *)btn
{
    [self.view endEditing:YES];
    for (UIButton *btn1 in self.btnArr) {
        if (btn.tag != btn1.tag) {
            btn1.selected = NO;
        }
    }
    
    if (btn.tag == 10) {
        self.selBtnType = 0;
        self.listSelArr = self.listAreaArr;
        btn.selected = !btn.selected;
    }
    if (btn.tag == 11) {
        self.selBtnType = 1;
        self.listSelArr = self.listDesArr;
        btn.selected = !btn.selected;
    }
    if (btn.tag == 12) {
        self.selBtnType = 2;
        self.listSelArr = self.listSortArr;
        btn.selected = !btn.selected;
    }
    
    self.headTableView.dataArr = self.listSelArr;
    self.headTableView.hidden = !btn.selected;
    [self ProductTypeViewAnimation:btn.selected];
    
}

// 地区按钮
- (void)leftButtonClick:(UIButton *)leftButton
{
    NSLog(@"地区按钮");
    [self.view endEditing:YES];
}

// 消息按钮
- (void)rightButtonClick:(UIButton *)rightButton
{
    NSLog(@"消息按钮");
    [self.view endEditing:YES];
    
    JMsgController *msgVC = [[JMsgController alloc]init];
    msgVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:msgVC animated:YES];
    
}
#pragma mark - request
/// 加载店铺数据
- (void)loadCutHairShopDataRequest
{
    NSString *url = @"BarberSh/GetSearchBarberShop";
    [JNetManager GetCutHairShopProductsRequedtUrl:url
                                      parameModel:self.headRequestModel
                                          success:^(id response) {
                                              if (response) {
                                                  JCutHairShopModel *model = response;
                                                  self.shopModel = model;
                                                  [self.dataArr addObjectsFromArray:model.shopModels];
                                                  
                                                  if (self.dataArr.count == 0) {
                                                      self.emptyView.hidden = NO;
                                                      self.tableView.hidden = YES;
                                                  }
                                                  else
                                                  {
                                                      self.emptyView.hidden = YES;
                                                      self.tableView.hidden = NO;
                                                      [self.tableView reloadData];

                                                  }
                                                  
                                              }
                                          } failure:^(NSString *err) {
                                              [SVProgressHUD showErrorWithStatus:err];
                                          }];
    
}

// 加载店铺 区域
- (void)loadCutHairShopAreaRequest
{
    NSString *url = @"BarberSh/GetAreasByCity";
    [JNetManager GetCutHairShopCityRequedtUrl:url
                                  shopNameTip:self.headRequestModel.City
                                      success:^(id response) {
                                          if (response) {
                                              NSMutableArray *mArr = [NSMutableArray arrayWithArray:response];
                                              [mArr insertObject:@"全城" atIndex:0];
                                              self.listAreaArr = [NSArray arrayWithArray:mArr];;

                                          }
                                      } failure:^(NSString *err) {
                                          [SVProgressHUD showErrorWithStatus:err];

                                      }];
}


#pragma mark - searchBar
// searchBar
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"===%@", searchBar.text);
    // 调用filterBySubstring:方法执行搜索
    //    [self filterBySubstring:searchBar.text];
    
    self.headRequestModel.ShopName = searchBar.text;
    self.headRequestModel.PageIndex = 1;
    [self.dataArr removeAllObjects];
    [self loadCutHairShopDataRequest];
    
    // 放弃作为第一个响应者，关闭键盘
    [searchBar resignFirstResponder];

}


- (void)ProductTypeViewAnimation:(BOOL)isShow
{
    if (isShow) {
        _headTableView.hidden = NO;
        
        [UIView animateWithDuration:0.3 animations:^{
            
            if (self.listSelArr.count > 0) {
                if (self.listSelArr.count * 44 > TableViewheight) {
                    self.headTableView.tableView.frame = CGRectMake(0, 0, self.contentView.width , TableViewheight- 100);
                }
                else
                {
                    self.headTableView.tableView.frame = CGRectMake(0, 0, self.contentView.width, self.listSelArr.count * 44);
                }
                
                
            }
        }];
    }
    else
    {
        [UIView animateWithDuration:0.3 animations:^{
            
            _headTableView.tableView.frame = CGRectMake(0, 0 , 0, 0);
            
            [self.headTableView setHidden:YES];
        }];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
